package compnents

import (
	"centerServer/models"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"sync"
)

var wxAccessTokenCompnentIns *WxAccessTokenCompnent
var atOnecSybc sync.Once

func GetWxAccessTokenCompnent() *WxAccessTokenCompnent {
	atOnecSybc.Do(func() {
		wxAccessTokenCompnentIns = &WxAccessTokenCompnent{AccessToken: ""}
		wxAccessTokenCompnentIns.Init()
	})
	return wxAccessTokenCompnentIns
}

// 专门用于刷新微信accessToken
type WxAccessTokenCompnent struct {
	AccessToken string
}

func (this *WxAccessTokenCompnent) Init() {
	this.RequestAccessToken()
}

func (this *WxAccessTokenCompnent) RequestAccessToken() {
	requestUrl := ACCESSTOKEN_URL + "grant_type=client_credential&appid=" + MACH_APPID + "&secret=" + MACH_APPSECRET
	httpReques, errA := HttpGet(requestUrl)
	if errA != nil {
		logs.Error("WxAccessTokenCompnent err :" + errA.Error())
	}
	defer httpReques.Body.Close()
	bodyByte, _ := ioutil.ReadAll(httpReques.Body)
	var requestBack models.RequstAccessToken
	jErr := json.Unmarshal(bodyByte, &requestBack)
	if jErr != nil {
		logs.Error("WxAccessTokenCompnent err :" + jErr.Error())
	}
	this.AccessToken = requestBack.AccessToken
}
